package com.hcrazy.manchester.app.services;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hcrazy.manchester.app.jdbc.ForumRuleDAO;
import com.hcrazy.manchester.app.pojo.ForumRule;

public class ForumRuleService {

	private ForumRuleDAO forumRuleDAO;
	
	
	public ForumRuleDAO getForumRuleDAO() {
		return forumRuleDAO;
	}

	public void setForumRuleDAO(ForumRuleDAO forumRuleDAO) {
		this.forumRuleDAO = forumRuleDAO;
	}
	
	public List<ForumRule> getAllRules() throws Exception {
		return forumRuleDAO.listAllRules();
	}
	
	public Map<Integer,ForumRule> getAllRulesInMap() throws Exception {
		List<ForumRule> list = forumRuleDAO.listAllRules();
		Map<Integer,ForumRule> map = new HashMap<Integer,ForumRule>();
		for(ForumRule rule:list){
			map.put(rule.getRuleType(), rule);
		}
		return map;
	}
	
	public ForumRule getById(int groupId) throws Exception {
		return forumRuleDAO.getById(groupId);
	}
	
	public void delForumRule(int groupId) throws Exception {
		forumRuleDAO.delForumRule(groupId);
	}
	
	public void updateForumRule(String ruleStr) throws Exception {
		if(null == ruleStr || "".equals(ruleStr))
			return;
		Gson gson = new Gson();
		Type type = new TypeToken<List<ForumRule>>(){}.getType();
		List<ForumRule> rules = gson.fromJson(ruleStr,type);
		
		forumRuleDAO.updateForumRule(rules);
	}
}
